import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/route_manager.dart';
import 'package:shudu/utils/global.dart';
import 'package:shudu/utils/image_utils.dart';
import 'package:shudu/viewmodel/play_viewmodel.dart';
import 'package:shudu/widget/operate_widget.dart';
import 'package:shudu/widget/sudoku/generator.dart';
import 'package:shudu/widget/sudoku/matrix.dart';

class PlayPage extends StatelessWidget {
  final PlayViewModel _viewModel;

  final LEVEL level;

  PlayPage(this.level) : _viewModel = Get.put(PlayViewModel(level));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: mainColor,
        elevation: 0,
        leading: GestureDetector(
          onTap: _viewModel.backPage,
          child: SizedBox(
            width: 24,
            child: loadAssetImage("icon_back", width: 24),
          ),
        ),
        title: const Text(
          "数独大师",
          style: TextStyle(fontSize: 17),
        ),
      ),
      body: WillPopScope(
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(15),
                decoration: const BoxDecoration(
                    color: mainColor,
                    borderRadius: BorderRadius.only(
                        bottomRight: Radius.circular(20),
                        bottomLeft: Radius.circular(20))),
                child: Column(
                  children: [
                    SizedBox(
                      width: Get.width,
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Positioned(
                              left: 0,
                              child: Text(
                                levelName[level] ?? "",
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 14,
                                ),
                              )),
                          Obx(() => Text(
                              durationStr(_viewModel.countdownNum.value),
                              style: const TextStyle(
                                  color: Colors.white, fontSize: 16))),
                          Positioned(
                              right: 0,
                              child: Obx(() => RichText(
                                      text: TextSpan(
                                          text: "错误：",
                                          style: const TextStyle(
                                              color: Colors.white,
                                              fontSize: 14),
                                          children: [
                                        TextSpan(
                                            text:
                                                "${_viewModel.errorNum.value}",
                                            style: const TextStyle(
                                                color: Color.fromRGBO(
                                                    255, 46, 95, 1))),
                                           const TextSpan(
                                                text:
                                                "/3")
                                      ])))),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    AspectRatio(
                      aspectRatio: 1,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Stack(
                          children: [
                            Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(8),
                                  border: Border.all(
                                      color: const Color(0xFFD7E1F4),
                                      width: 2)),
                              child: Obx(() => GridView.builder(
                                  shrinkWrap: true,
                                  physics: const NeverScrollableScrollPhysics(),
                                  itemCount: _viewModel.puzzles.length,
                                  gridDelegate:
                                      const SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 9),
                                  itemBuilder:
                                      ((BuildContext context, int index) {
                                    onTap() {
                                      _viewModel.selIndex.value = index;
                                    }

                                    return _itemWidget(index,
                                        _viewModel.puzzles[index], onTap);
                                  }))),
                            ),
                            Obx(() => _viewModel.pause.value
                                ? OperateWidget(
                                    block: (index) {
                                      _viewModel.operateClick(index);
                                    },
                                  )
                                : const SizedBox())
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              _btmWidget()
            ],
          ),
          onWillPop: () async {
            return false;
          }),
    );
  }

  Widget _btmWidget() {
    return SizedBox(
      height: 150,
      child: Row(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: _viewModel.remind,
                    child: Stack(
                      children: [
                        loadAssetImage("icon_info", width: 32),
                        Positioned(
                            right: 0,
                            child: Container(
                              width: 17,
                              height: 17,
                              alignment: Alignment.center,
                              decoration: const BoxDecoration(
                                  color: Color(0xFFFF2E5F),
                                  shape: BoxShape.circle),
                              child: Obx(() => Text(
                                    "${_viewModel.remindNum.value}",
                                    style: const TextStyle(
                                      fontSize: 12,
                                      color: Colors.white,
                                    ),
                                  )),
                            ))
                      ],
                    ),
                  ),
                  GestureDetector(
                    onTap: _viewModel.reset,
                    child: loadAssetImage("icon_reset", width: 32),
                  )
                ],
              ),
            ),
          ),
          SizedBox(
            width: Get.width * 0.6,
            child: Wrap(
              children: List.generate(
                  9,
                  (index) => GestureDetector(
                        onTap: () {
                          _viewModel.fillNum(index + 1);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: (Get.width * 0.2).floorToDouble(),
                          height: 50,
                          child: Text(
                            "${index + 1}",
                            style: const TextStyle(
                                color: mainColor,
                                fontWeight: FontWeight.w700,
                                fontSize: 32),
                          ),
                        ),
                      )),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: _viewModel.clickPause,
                    child: Obx(() => loadAssetImage(
                        _viewModel.pause.value ? "icon_start" : "icon_pause",
                        width: 32)),
                  ),
                  GestureDetector(
                    onTap: _viewModel.clearItem,
                    child: loadAssetImage("icon_clear", width: 32),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  BorderSide singleSide = const BorderSide(width: 1, color: Color(0xFFD7E1F4));
  BorderSide doubleSide = const BorderSide(width: 2, color: Color(0xFFD7E1F4));

  Widget _itemWidget(int index, int value, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Obx(() => Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              border: borderWithIndex(index),
            ),
            child: Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: _itemBgColor(index),
                  borderRadius: BorderRadius.circular(
                      index == _viewModel.selIndex.value ? 4 : 0)),
              child: Text(
                value == -1 ? "" : value.toString(),
                style: TextStyle(
                    color: _textColor(index),
                    fontSize: 26,
                    fontWeight: FontWeight.w700),
              ),
            ),
          )),
    );
  }

  Color _textColor(int index) {
    Color color = Colors.black;
    if (_viewModel.isOnlyReadBox(index)) {
      color = Colors.black;
    } else {
      if (_viewModel.isCorrect(index)) {
        if (_viewModel.selIndex.value == index) {
          color = Colors.white;
        } else {
          color = mainColor;
        }
      } else {
        color = Colors.red;
      }
    }
    return color;
  }

  Border borderWithIndex(int index) {
    bool isNoBottomLine = index >= 72;
    bool isDoubleBottomLine =
        ((index >= 18 && index <= 26) || (index >= 45 && index <= 53));
    bool isNoLeftLine = index % 9 == 0;
    bool isDoubleLeftLine = index % 3 == 0;
    return Border(
        bottom: (isNoBottomLine
            ? BorderSide.none
            : isDoubleBottomLine
                ? doubleSide
                : singleSide),
        left: isNoLeftLine
            ? BorderSide.none
            : (isDoubleLeftLine ? doubleSide : singleSide));
  }

  Color _itemBgColor(int index) {
    Color bgColor;
    List<int> zoneIndexes =
        Matrix.getZoneIndexes(zone: Matrix.getZone(index: index));
    List<int> rowIndexes = Matrix.getRowIndexes(Matrix.getRow(index));
    List<int> colIndexes = Matrix.getColIndexes(Matrix.getCol(index));

    Set indexSet = {};
    indexSet.addAll(zoneIndexes);
    indexSet.addAll(rowIndexes);
    indexSet.addAll(colIndexes);

    if (index == _viewModel.selIndex.value) {
      bgColor = mainColor;
    } else if (indexSet.contains(_viewModel.selIndex.value)) {
      bgColor = mainColor.withOpacity(0.1);
    } else {
      bgColor = Colors.white;
    }
    return bgColor;
  }
}
